package com.voxel.sense.infomsg.module.firm.details.average;

import android.text.TextUtils;

import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.ToastUtil;
import com.voxel.sense.infomsg.App;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.base.RecyclerViewPresenter;
import com.voxel.sense.infomsg.data.bean.AverageDataBean;
import com.voxel.sense.infomsg.data.bean.MultiItemBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.AverageEntity;
import cyy.example.com.facotry.net.helper.FirmNetHelper;

/**
 * Created by ChenYiYao on 2018/10/30.
 * des :
 */
public class DataAveragePresenter extends RecyclerViewPresenter<DataAverageContract.View>
        implements DataAverageContract.Presenter, DataSource.Callback<BaseEntity<AverageEntity>> {


    private String mId;
    private int mType;
    private String mStartTime;
    private String mEndTime;

    public DataAveragePresenter(DataAverageContract.View view) {
        super(view);
    }

    @Override
    protected void loadData() {
        FirmNetHelper.getAverageValue(mType + "", mId, mStartTime, mEndTime, getPAGE_NUMB() + "", getPageDataSize() + "", this);
    }

    @Override
    protected void loadMoreData() {
        FirmNetHelper.getAverageValue(mType + "", mId, mStartTime, mEndTime, getPAGE_NUMB() + "", getPageDataSize() + "", this);
    }

    @Override
    public void doLoadMore() {
        startLoadMoreData();
    }

    @Override
    public void doRefresh(String id, int type, String startTime, String endTime) {

        if (loadMoreIng || refreshIng) {
            ToastUtil.showToastLong(Factory.app(), App.getInstance().getString(R.string.network_load_data));
        } else if (TextUtils.isEmpty(startTime)) {
            ToastUtil.showToastLong(Factory.app(), App.getInstance().getString(R.string.pleas_pick_start_time));
        } else if (TextUtils.isEmpty(endTime)) {
            ToastUtil.showToastLong(Factory.app(), App.getInstance().getString(R.string.pleas_pick_end_time));
        } else {
            mId = id;
            mType = type;
            Date startDate = new Date();
            Date endDate = new Date();
            if (mType == DataAverageContract.VALID_DAY_AVG || mType == DataAverageContract.DAY_AVG) {
                //有效日均值或日均值
                //开始时间选择时间的零点
                Date s = TimeUtils.string2Date(startTime, new SimpleDateFormat(Constants.TimeYMDFormat));
                startDate = TimeUtils.getStartOfDay(s);

                //结束时间为改天时间的最后时刻
                Date e = TimeUtils.string2Date(endTime, new SimpleDateFormat(Constants.TimeYMDFormat));
                endDate = TimeUtils.getEndOfDay(e);
            } else if (mType == DataAverageContract.MONTH_AVG) {
                //月均值
                //开始时间为该月份的第一天的零食
                Date s = TimeUtils.string2Date(startTime, new SimpleDateFormat(Constants.TimeYMFormat));
                startDate = TimeUtils.getStartOfDay(TimeUtils.getFirstDayDateOfMonth(s));

                //解释时间为该月份的最后一天的最后一刻
                Date e = TimeUtils.string2Date(endTime, new SimpleDateFormat(Constants.TimeYMFormat));
                endDate = TimeUtils.getEndOfDay(TimeUtils.getLastDayOfMonth(e));

            } else if (mType == DataAverageContract.YEAR_AVG) {
                //年均值
                Date s = TimeUtils.string2Date(startTime, new SimpleDateFormat("yyyy"));
                startDate = TimeUtils.getStartOfDay(TimeUtils.getFirstDayDateOfMonth(s));

                Date e = TimeUtils.string2Date(endTime, new SimpleDateFormat("yyyy"));
                if (e.getYear() == TimeUtils.getNowDate().getYear()) {
                    //如何时间是当前的年月，那结束时间是当前时刻
                    endDate = TimeUtils.getNowDate();
                } else {
                    endDate = TimeUtils.getEndOfYear(s);
                }
            }

            if (startDate.getTime() > endDate.getTime()) {
                //时间选择不正确
                ToastUtil.showToastLong(Factory.app(), App.getInstance().getString(R.string.start_cannot_more_than_end));
            } else {
                mStartTime = TimeUtils.date2String(startDate, new SimpleDateFormat(Constants.REAL_DATA_TIME_FORMAT_TYPE));
                mEndTime = TimeUtils.date2String(endDate, new SimpleDateFormat(Constants.REAL_DATA_TIME_FORMAT_TYPE));
                mView.showLoading("");
                startRefreshData();
            }
        }
    }

    @Override
    public void onDataLoaded(BaseEntity<AverageEntity> data, int reqId) {
        if (mView == null) return;

        if (data.isSuccess() && data != null && mType != -1) {
            List<MultiItemBean> multiItemBeans = handlerAverageData(data.getData());
            loadDataComplete(multiItemBeans);
        } else {
            LoadDataFailure();
        }
    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView == null) return;

        LoadDataFailure();
        mView.showEmptyView(Factory.app().getString(R.string.data_rsp_error),true);
    }

    private List<MultiItemBean> handlerAverageData(AverageEntity data) {
        List<MultiItemBean> list = new ArrayList();

        List<AverageEntity.ParamStatisticAvgObjListBean> avgValueList = data.getParamStatisticAvgObjList();
        AverageEntity.SiteStandValueVoBean siteStandValueVo = data.getSiteStandValueVo();

        if (avgValueList != null && avgValueList.size() > 0 && siteStandValueVo != null
                && siteStandValueVo.getParamThirftObjectList() != null && siteStandValueVo.getParamThirftObjectList().size() > 0) {
            //将单位等信息提取出来
            Map<String, AverageEntity.SiteStandValueVoBean.ParamThirftObjectListBean> paramInfos = new HashMap<>();
            List<AverageEntity.SiteStandValueVoBean.ParamThirftObjectListBean> paramThirftObjectList = siteStandValueVo.getParamThirftObjectList();

            for (AverageEntity.SiteStandValueVoBean.ParamThirftObjectListBean bean : paramThirftObjectList) {
                paramInfos.put(bean.getParamCode(), bean);
            }

            //遍历每个时间点
            for (AverageEntity.ParamStatisticAvgObjListBean valueBean : avgValueList) {
                List<AverageDataBean> dataListBeans = new ArrayList<>();
                Map<String, String> paramCodeValue = valueBean.getParamCodeValue();
                if (paramCodeValue != null) {
                    Set<String> keys = paramCodeValue.keySet();
                    for (String key : keys) {
                        //遍历每个时间点下的每一个元素
                        AverageEntity.SiteStandValueVoBean.ParamThirftObjectListBean bean = paramInfos.get(key);
                        if (bean != null) {
                            String time = getFormatDateStr(valueBean.getTime());
                            AverageDataBean averageDataBean = new AverageDataBean(bean.getParamUnit(),
                                    bean.getParamName(), time, paramCodeValue.get(key), bean.getParamValue());
                            dataListBeans.add(averageDataBean);
                        }
                    }
                }
                if (dataListBeans.size() > 0) {
                    MultiItemBean itemBean = new MultiItemBean(dataListBeans, mType);
                    list.add(itemBean);
                }
            }
        }
        return list;
    }

    private String getFormatDateStr(String time) {
        String str = time;
        if (TextUtils.isEmpty(time)) {

        } else if (mType == DataAverageContract.YEAR_AVG) {
//            TimeUtils.getString(time,new SimpleDateFormat("yyyy"),0,TimeConstants.DAY);
        } else if (mType == DataAverageContract.MONTH_AVG) {
            str = TimeUtils.date2String(TimeUtils.string2Date(time, new SimpleDateFormat("yyyyMM")), new SimpleDateFormat(Constants.TimeYMFormat));
        } else if (mType == DataAverageContract.DAY_AVG || mType == DataAverageContract.VALID_DAY_AVG) {
            str = TimeUtils.date2String(TimeUtils.string2Date(time, new SimpleDateFormat("yyyyMMdd")), new SimpleDateFormat(Constants.TimeYMDFormat));
        }

        return str;
    }
}
